import React, { Component } from 'react'
// 验证数据类型
import PropTypes from 'prop-types'
// 引入关联的actions/postActions
import { creatPost } from '../actions/postActions'
// 引入connect 用于从ui组件生成容器组件,意思将两种组件连起来(将postActions和posts.js文件进行连接)
import { connect } from 'react-redux'
class postForm extends Component {
    constructor(props) {
        super(props)
        this.state = {
            title: '',
            body: ''
        }
    }
    onChange = (e) => {
        /**
         * 赋值
         */
        this.setState({ [e.target.name]: e.target.value })

    }
    onSubmit = (e) => {
        e.preventDefault()
        const post = {
            title: this.state.title,
            body: this.state.body
        }
        //点击保存后触发action
        this.props.creatPost(post)
        // 因为生命周期的问题 ,在这里是拿不到值,应该在componentWillReceiveProps()方法中拿,渲染组件是posts.js可以写在posts页面
        // console.log(this.props.item);
    }
    render() {
        return (
            <div>
                <h1>添加内容</h1>
                <form onSubmit={this.onSubmit}>
                    <div>
                        <label>
                            title
                        </label>
                        <br />
                        <input type="text" name="title" onChange={this.onChange} value={this.state.title}></input>
                    </div>
                    <div>
                        <label>
                            body
                        </label>
                        <br />
                        <textarea name="body" onChange={this.onChange} value={this.state.body}></textarea>
                    </div>
                    <br />
                    <button type="submit"> 添加</button>
                </form>
            </div>
        )
    }
}
postForm.propTypes = {
    creatPost: PropTypes.func.isRequired,
    
}
const mapStateToProps = state => ({
    item: state.posts.item
})
export default connect(mapStateToProps, { creatPost })(postForm)